package com.ja.openchat.ui.chat.group;

import android.text.TextUtils;

import com.zy.openchat.core.model.group.JsoupTaskEvent;
import com.zy.openchat.core.model.message.HtmlDocumentInfo;

import org.greenrobot.eventbus.EventBus;
import org.jetbrains.annotations.NotNull;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

public class JsoupTaskCallback {

    public static HashMap<String,JsoupTaskCallback> htmlCache = new HashMap();

    public static HtmlDocumentInfo check(String url){
        String mUrl = checkUrl(url);
        JsoupTaskCallback taskCallback = htmlCache.get(mUrl);
        if(taskCallback!=null){
            if(taskCallback.htmlDocumentInfo!=null){
                return taskCallback.htmlDocumentInfo;
            }
        }else{
            taskCallback = new JsoupTaskCallback(url);
            taskCallback.analyze();
            htmlCache.put(mUrl,taskCallback);
        }
        return null;
    }


    public static String checkUrl(String checkUrl){
        String newUrl = checkUrl;
        if (checkUrl.startsWith("http://"))
            newUrl = checkUrl;

        if (checkUrl.startsWith("www"))
            newUrl = "http://" + checkUrl;

        return newUrl;
    }

    public String orgiUrl;

    public String url;

    public void analyze(){
        Observable.create(new ObservableOnSubscribe<Document>() {

            @Override
            public void subscribe(@NotNull ObservableEmitter<Document> emitter) throws Exception {
                try {
                    Document doc = Jsoup.connect(url).get();
                    emitter.onNext(doc);
                    emitter.onComplete();
                }catch (Exception e){
                    //Malformed URL: www.baidu.com
                    emitter.onError(e);
                }
            }
        }) .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Document>() {
                    @Override
                    public void accept(Document doc) throws Exception {
                        htmlDocumentInfo = new HtmlDocumentInfo();
                        try {

                            htmlDocumentInfo.title = doc.title();
                            Element head = doc.head();
                            htmlDocumentInfo.content = head.getElementsByAttributeValueContaining("name","description").attr("content");
                            String icon = head.getElementsByAttributeValue("rel","icon").attr("href");
                            if(TextUtils.isEmpty(icon)){
                                icon = head.getElementsByAttributeValueContaining("rel","icon").attr("href");
                            }
                            if(icon.startsWith("//")){
                                icon = icon.replaceFirst("//","");
                            }
                            htmlDocumentInfo.icon = checkUrl(icon);
                        }catch (Exception e){
                            e.printStackTrace();
                        }
                        EventBus.getDefault().post(new JsoupTaskEvent(url,htmlDocumentInfo));
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {

                    }
                });

    }

    public HtmlDocumentInfo htmlDocumentInfo;

    public List<JsoupCallback> callbacks;

    public JsoupTaskCallback(String url) {
        this.orgiUrl = url;
        this.url = checkUrl(url);
        callbacks = new ArrayList<>();
    }

    public void append(JsoupCallback callback){
        callbacks.add(callback);
    }

}
